package demo.java.net;

import com.alibaba.fastjson.JSON;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class URIDemo {

    public static String appendParam(String uri, String appendParamName, String appendParam) {
        String[] array = uri.split("\\?");
        System.out.println(array[0]);
        System.out.println(array[1]);
        String query = array[1];
        Map<String, String> queryMap = parseParameters(query);
        String paramValue = queryMap.get(appendParamName);
        if (paramValue == null) {
            return uri;
        }
        if (paramValue.contains("?")) {
            paramValue += "&" + appendParam;
        } else {
            paramValue += "?" + appendParam;
        }
        queryMap.put(appendParamName, paramValue);

        String newQuery = queryMap.entrySet().stream()
                .map(en -> String.format("%s=%s", en.getKey(), urlEncode(en.getValue())))
                .collect(Collectors.joining("&"));
        String newStr = array[0] + "?" + newQuery;
        System.out.println(newStr);
        return newStr;
    }

    /**
     * URL encode
     *
     * @param param
     * @return
     */
    public static String urlEncode(String param) {
        try {
            return URLEncoder.encode(param, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return param;
        }
    }

    /**
     * 将参数存入map集合
     *
     * @param query url地址
     * @return url请求参数部分存入map集合
     */
    public static Map<String, String> parseParameters(String query) {
        if (query == null || query.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, String> mapRequest = new HashMap<>();
        String[] arrSplit = query.split("&");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = strSplit.split("=");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], URLDemo.urlDecode(arrSplitEqual[1]));
            } else {
                if (!arrSplitEqual[0].isEmpty()) {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    /**
     * 打印URI相关信息
     *
     * @param uri
     */
    public static void printURI(URI uri) {
        if (uri == null) {
            return;
        }
        System.out.println("-------------------\n uri = " + uri.toString());
        System.out.println();
        System.out.println("toJson = " + JSON.toJSONString(uri, true));

        boolean isAbsolute = uri.isAbsolute();
        boolean isOpaque = uri.isOpaque();
        int port = uri.getPort();
        String host = uri.getHost();
        System.out.println(
                "host = " + host + " , port = " + port + " , isAbsolute = " + isAbsolute + " , isOpaque = " + isOpaque);
        System.out.println();
        String authority = uri.getAuthority();
        String rawAuthority = uri.getRawAuthority();
        System.out.println("authority = " + authority + " , rawAuthority = " + rawAuthority);
        System.out.println();
        String fragment = uri.getFragment();
        String rawFragment = uri.getRawFragment();
        System.out.println("fragment = " + fragment + " , rawFragment = " + rawFragment);
        System.out.println();
        String path = uri.getPath();
        String rawPath = uri.getRawPath();
        System.out.println("path = " + path + " , rawPath = " + rawPath);
        System.out.println();
        String query = uri.getQuery();
        String rawQuery = uri.getRawQuery();
        System.out.println("query = " + query + " , rawQuery = " + rawQuery);
        System.out.println();
        String rawSchemeSpecificPart = uri.getRawSchemeSpecificPart();
        String schemeSpecificPart = uri.getSchemeSpecificPart();
        String scheme = uri.getScheme();
        System.out.println("scheme = " + scheme + " , schemeSpecificPart = " + schemeSpecificPart
                + " , rawSchemeSpecificPart = " + rawSchemeSpecificPart);
        System.out.println();
        String rawUserInfo = uri.getRawUserInfo();
        String userInfo = uri.getUserInfo();
        System.out.println("userInfo = " + userInfo + " , rawUserInfo = " + rawUserInfo);


    }

    @Test
    public void print() throws URISyntaxException {
        String str = "http://sh-nh-b2-3-q15-rabbitmq-9-24:15672/api/queues";
        try {
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }

        str = "http://xdcs.ximalaya.com/app_info?app_name=recsys-stream-query&anchor_point=attribution_alert&startTime=1564041900000&endTime=1564043700000&serviceId=/recsys/onekey/rec/scene/home/page/top/tracks";
        try {
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            str = "http://sh-nh-b2-3-q15-rabbitmq-9-24:15672/api/queues?email=junying.han@ximalaya.com&id=7150";
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            str = "http://sh-nh-b2-3-q15-rabbitmq-9-24:15672/api/queues?URI=http://qcloud-shanghai-4-tfserving:7537/tf-serving-proxy/healthcheck";
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Test
    public void test2() throws UnsupportedEncodingException {
        String query = "none:db_monitor_sample{app=*,dbUrl=*,dbName=*}";
        String str = "http://xdcs.ximalaya.com/tsdb/api/query?m=";
        try {
            printURI(new URI(str + URLEncoder.encode(query, "utf-8")));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        try {
            printURI(new URI(str + query));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test() {
        String str = "http://localhost:8080/as/image/banner/2/5.2.1.0?id=123#99";
        try {
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testMultiHost1() throws URISyntaxException {
        String str = "http://app1,app2:15672";
        try {
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }
        str = "http://app1:80,app2:80";
        try {
            printURI(new URI(str));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void testJdbc() {
        String str = "jdbc:mysql://mysql-xima-096:3306/ting";
        try {
            URI uri = URI.create(str);
            printURI(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    @Test
    public void testAppendParam() throws URISyntaxException {
        String str = "dingtalk://dingtalkclient/page/link?pc_slide=true&url=https%3A%2F%2Fxdcs.ximalaya.com%2Fgatekeeper%2Fxdcs-h5%23%2FsouthgateScale";

        printURI(new URI(str));
        System.out.println();
        printURI(new URI(appendParam(str, "url", "a=b")));
    }


}
